package main.java.jdbc3;



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;


/**
 * @Auther:Liu
 * @Testname:useTrascation
 * @Date:2025/3/12 16:28
 */


    public class userStransction {

        //事务来解决
        public void useTransaction() throws Exception {
// 1. 得到连接
            Connection connection=null;
//2. 组织一个 sql
            String sql = "update stu_student set stu_age = stu_age-10 where stu_id = 1";
            String sql2 = "update stu_student set stu_age = stu_age+10  where stu_id = 2";
            PreparedStatement preparedStatement = null;
//3. 创建 PreparedStatement 对象

            try {
                String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC";
                String username = "root";
                String password = "123456";
                connection = DriverManager.getConnection(url, username, password);
//将 connection 设置为不自动提交
                connection.setAutoCommit(false); //开启了事务
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.executeUpdate(); // 执行第1 条sql

                int i = 1 / 0; //抛出异常

                preparedStatement = connection.prepareStatement(sql2);
                preparedStatement.executeUpdate(); // 执行第3 条sql//这里提交事务

                connection.commit();
            } catch (Exception e) { //这里我们可以进行回滚，即撤销执行的 SQL
// 默认回滚到事务开始的状态.
                System.out.println("执行发生了异常，撤销执行的sql");
                try {
                    connection.rollback();
                } catch (Exception throwables) {
                    throwables.printStackTrace();
                }
                e.printStackTrace();
            }finally {
                //关闭资源
                preparedStatement.close();
                connection.close();
            }
        }
    }

